package ke.me.muhia.spring.masomo.provisioning;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Vector;

import ke.me.muhia.spring.masomo.provisioning.ucip.CustomMethods;
import ke.me.muhia.spring.masomo.provisioning.ucip.UCIPParameters;
import org.apache.xmlrpc.client.XmlRpcClient;
import org.apache.xmlrpc.client.XmlRpcClientConfigImpl;
import org.apache.xmlrpc.client.XmlRpcSunHttpTransport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;

@Configuration
@ComponentScan
@EnableAutoConfiguration
public class MasomosApplication extends SpringBootServletInitializer {

//    private final Logger logger = LoggerFactory.getLogger(getClass());

    
    @Bean
    public PropertySourcesPlaceholderConfigurer configurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }

    @Bean @Autowired
    public UCIPParameters parameters() {
        UCIPParameters params =  new UCIPParameters();
        logger.debug("Agent used is "+params.getUserAgent());
        return params;
    }

    public CustomMethods initMethods() {
        return new CustomMethods();
    }
    
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application){
        return application.sources(MasomosApplication.class);        
    }
    
    

//    @SuppressWarnings({"rawtypes", "unchecked", "unchecked"})
//    @Override
//    public void run(String... args) throws Exception {
//        // methods = new CustomMethods();
//        try {
//            SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyyHHmmssSSS");
//            Calendar cal = Calendar.getInstance();
//            XmlRpcClientConfigImpl config = initMethods().createXmlRpcConfig(parameters());
//            XmlRpcClient client = initMethods().createXmlRpcClient(config);
//            XmlRpcSunHttpTransport transport = initMethods().createTransport(client);
//            String transactionid = sdf.format(cal.getTime());
//            Vector v = initMethods().createGetBalanceandDateHash(1, "EXT", "web2sms2", transactionid, new Date(), "254736094292");
////            String methodName = "GetBalanceAndDate";
//
//            HashMap o = initMethods().getBalanceAndDateResp(initMethods().xmlRpcMethodExecutor(config, transport, v, "GetBalanceAndDate"));
//
//            if (o != null && o.containsKey("responseCode")) {
//                if (o.get("responseCode").equals("0")) {
//                    //Transaction was successful
//                    /**
//                     * TODO: Increment total success for scheduled jobs
//                     */
//                    logger.info("Transaction: " + o.get("originTransactionID").toString() + " succeeded.");
//
//                } else {
//                    //Transaction Failed
//                    /**
//                     * TODO: Increment total failure for scheduled jobs
//                     *
//                     */
//                    logger.info("Transaction: " + o.get("originTransactionID").toString() + " failed with errorcode: " + o.get("responseCode").toString() + ".");
//                }
//
//            } else {
//                //Invalid Response was received
//                /**
//                 * TODO: Increment total invalid for scheduled jobs
//                 *
//                 */
//                logger.info("Transaction: " + o.get("originTransactionID").toString() + " returned an invalid response.");
//
//            }
//
//            logger.info("Account balance is: " + o.toString());
//
//        } catch (Exception ex) {
//            logger.error(ex.getMessage(), ex);
//        }
//
//    }

////    @SuppressWarnings({"unchecked", "rawtypes"})
//    public HashMap GetBalanceAndDate(int tsubscriberNumberNAI,
//            String tOriginNodeType, String tOriginHostName,
//            String tOriginTransactionID, Date tOriginTimeStamp,
//            String tSubscriberNumber) {
//        // HashMap<String, Object> o = null;
//        HashMap o = new HashMap<>();
//        Hashtable htElements = new Hashtable<>();
//        // List<?> o = null;
//        try {
//
//            XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
//            config.setServerURL(new URL(parameters().getStrURL()));
//            config.setEnabledForExceptions(true);
//            config.setBasicUserName(parameters().getuName());
//            config.setBasicPassword(parameters().getuPass());
//            config.setEncoding(XmlRpcClientConfigImpl.UTF8_ENCODING);
//            config.setReplyTimeout(parameters().getReplyTimeout());
//            config.setUserAgent(parameters().getUserAgent());
//            config.setConnectionTimeout(parameters().getConnectTimeout());
//            config.setContentLengthOptional(true);
//            // config.setEnabledForExtensions(true);
//
//            XmlRpcClient client = new XmlRpcClient();
//
//            // XmlRpcSunHttpTransport http = (XmlRpcSunHttpTransport) new
//            // CustomXmlRpcSunTransportFactory(client).getTransport();
//            MessageLoggingTransport http = new MessageLoggingTransport(client);
//            // XmlRpcSunHttpTransport http = new XmlRpcSunHttpTransport(client);
//            client.setTypeFactory(new CustomTypeFactory(client));
//            client.setConfig(config);
//            client.setTransportFactory(new CustomXmlRpcSunTransportFactory(client));
//
//            Hashtable request = new Hashtable();
//            request.put("originNodeType", tOriginNodeType);
//            request.put("originHostName", tOriginHostName);
//            request.put("originTransactionID", tOriginTransactionID);
//            request.put("originTimeStamp", tOriginTimeStamp);
//            request.put("subscriberNumberNAI", tsubscriberNumberNAI);
//            request.put("subscriberNumber", tSubscriberNumber);
//
//            Vector v = new Vector();
//            v.add(request);
//
//            o = (HashMap) http.sendRequest(new XmlRpcClientRequestImpl(config, "GetBalanceAndDate", v));
//
//            // ByteArrayOutputStream bos = new ByteArrayOutputStream();
//            // XMLEncoder xmlEncoder = new XMLEncoder(bos);
//            // xmlEncoder.writeObject(o);
//            // xmlEncoder.flush();
//            // String xmlout =o.toString();
//            // logger.info("the xml is: "+xmlout);
//            // htElements = initMethods().returnElements(xmlout);
//        } catch (MalformedURLException | XmlRpcException ex) {
//            // TODO Auto-generated catch block
//            logger.error(ex.getMessage(), ex);
//        }
//        return o;
//    }
    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(MasomosApplication.class);
        
        app.setShowBanner(true);

        app.run(args);
    }
}
